{% extends "base.html" %}

{% block title %}创建预约 - 乒乓球培训管理系统{% endblock %}

{% block page_title %}创建预约{% endblock %}

{% block extra_css %}
<style>
    .form-container {
        max-width: 800px;
        margin: 0 auto;
    }

    .step-indicator {
        display: flex;
        justify-content: center;
        margin-bottom: 30px;
    }

    .step {
        flex: 1;
        text-align: center;
        position: relative;
        padding: 10px;
    }

    .step:not(:last-child)::after {
        content: '';
        position: absolute;
        top: 25px;
        right: 0;
        width: 100%;
        height: 2px;
        background: #dee2e6;
        z-index: 1;
    }

    .step.active::after {
        background: #007bff;
    }

    .step.completed::after {
        background: #28a745;
    }

    .step-circle {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: #dee2e6;
        color: #6c757d;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 10px;
        position: relative;
        z-index: 2;
        font-weight: bold;
    }

    .step.active .step-circle {
        background: #007bff;
        color: white;
    }

    .step.completed .step-circle {
        background: #28a745;
        color: white;
    }

    .form-section {
        background: white;
        border-radius: 8px;
        padding: 30px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .coach-card {
        border: 2px solid #e9ecef;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .coach-card:hover {
        border-color: #007bff;
        background: #f8f9ff;
    }

    .coach-card.selected {
        border-color: #007bff;
        background: #e3f2fd;
    }

    .coach-avatar {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        object-fit: cover;
    }

    .time-slot {
        border: 1px solid #dee2e6;
        border-radius: 6px;
        padding: 8px 12px;
        margin: 5px;
        cursor: pointer;
        transition: all 0.2s ease;
        display: inline-block;
        min-width: 80px;
        text-align: center;
    }

    .time-slot:hover {
        border-color: #007bff;
        background: #f8f9ff;
    }

    .time-slot.selected {
        background: #007bff;
        color: white;
        border-color: #007bff;
    }

    .time-slot.disabled {
        background: #f8f9fa;
        color: #6c757d;
        cursor: not-allowed;
        border-color: #e9ecef;
    }

    .table-card {
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .table-card:hover {
        border-color: #007bff;
        box-shadow: 0 2px 8px rgba(0,123,255,0.1);
    }

    .table-card.selected {
        border-color: #007bff;
        background: #f8f9ff;
    }

    .price-summary {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        margin-top: 20px;
    }

    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255,255,255,0.8);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }

    .error-message {
        background: #f8d7da;
        border: 1px solid #f5c6cb;
        color: #721c24;
        padding: 10px 15px;
        border-radius: 6px;
        margin-bottom: 15px;
        display: none;
    }

    .success-message {
        background: #d4edda;
        border: 1px solid #c3e6cb;
        color: #155724;
        padding: 10px 15px;
        border-radius: 6px;
        margin-bottom: 15px;
        display: none;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="form-container">
        <!-- 返回按钮 -->
        <div class="mb-3">
            <a href="{{ url_for('student_reservations.index') }}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> 返回预约列表
            </a>
        </div>

        <!-- 步骤指示器 -->
        <div class="step-indicator">
            <div class="step active" id="step1">
                <div class="step-circle">1</div>
                <div>选择教练</div>
            </div>
            <div class="step" id="step2">
                <div class="step-circle">2</div>
                <div>选择时间</div>
            </div>
            <div class="step" id="step3">
                <div class="step-circle">3</div>
                <div>选择球台</div>
            </div>
            <div class="step" id="step4">
                <div class="step-circle">4</div>
                <div>确认预约</div>
            </div>
        </div>

        <!-- 错误提示 -->
        <div class="error-message" id="errorMessage"></div>
        <div class="success-message" id="successMessage"></div>

        <!-- 预约表单 -->
        <form method="POST" id="reservationForm">
            {{ form.hidden_tag() }}

            <!-- 第一步：选择教练 -->
            <div class="form-section" id="section1">
                <h5 class="mb-3">
                    <i class="bi bi-person-check"></i> 选择教练
                </h5>
                <p class="text-muted mb-4">请选择您要预约的教练（只能选择已建立师生关系的教练）</p>

                <div id="coachList">
                    {% if form.coach_id.choices|length > 1 %}
                        {% for value, label in form.coach_id.choices %}
                            {% if value %}
                                <div class="coach-card" data-coach-id="{{ value }}" onclick="selectCoach('{{ value }}')">
                                    <div class="row align-items-center">
                                        <div class="col-auto">
                                            <div class="coach-avatar bg-success d-flex align-items-center justify-content-center text-white">
                                                <i class="bi bi-person-check"></i>
                                            </div>
                                        </div>
                                        <div class="col">
                                            <h6 class="mb-1">{{ label.split(' - ')[0] }}</h6>
                                            <small class="text-muted">
                                                {{ label.split(' - ')[1] if ' - ' in label else '教练' }}
                                            </small>
                                        </div>
                                        <div class="col-auto">
                                            <i class="bi bi-check-circle text-success" style="display: none;"></i>
                                        </div>
                                    </div>
                                </div>
                            {% endif %}
                        {% endfor %}
                    {% else %}
                        <div class="alert alert-warning">
                            <i class="bi bi-exclamation-triangle"></i>
                            暂无可选教练，请先与教练建立师生关系。
                            <a href="{{ url_for('student_coach.search') }}" class="alert-link">去寻找教练</a>
                        </div>
                    {% endif %}
                </div>

                <!-- 使用form字段而不是独立的hidden input -->
                {{ form.coach_id }}

                <div class="text-end mt-3">
                    <button type="button" class="btn btn-primary" onclick="nextStep(1)" disabled id="nextBtn1">
                        下一步 <i class="bi bi-arrow-right"></i>
                    </button>
                </div>
            </div>

            <!-- 第二步：选择时间 -->
            <div class="form-section" id="section2" style="display: none;">
                <h5 class="mb-3">
                    <i class="bi bi-calendar3"></i> 选择时间
                </h5>
                <p class="text-muted mb-4">请选择预约日期和时间段</p>

                <div class="row">
                    <div class="col-md-6">
                        <label class="form-label">预约日期</label>
                        {{ form.reservation_date(class="form-control", onchange="loadTimeSlots()") }}
                        {% if form.reservation_date.errors %}
                            <div class="text-danger small mt-1">
                                {% for error in form.reservation_date.errors %}
                                    {{ error }}
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">课程时长</label>
                        <select class="form-select" id="durationSelect" onchange="updateEndTime()">
                            <option value="60">1小时</option>
                            <option value="90">1.5小时</option>
                            <option value="120">2小时</option>
                        </select>
                    </div>
                </div>

                <div class="mt-4">
                    <label class="form-label">开始时间</label>
                    <div id="timeSlots" class="mt-2">
                        <div class="text-muted">请先选择日期</div>
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-6">
                        <label class="form-label">开始时间</label>
                        {{ form.start_time(class="form-control", readonly="readonly") }}
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">结束时间</label>
                        {{ form.end_time(class="form-control", readonly="readonly") }}
                    </div>
                </div>

                <div class="text-end mt-3">
                    <button type="button" class="btn btn-outline-secondary me-2" onclick="prevStep(2)">
                        <i class="bi bi-arrow-left"></i> 上一步
                    </button>
                    <button type="button" class="btn btn-primary" onclick="nextStep(2)" disabled id="nextBtn2">
                        下一步 <i class="bi bi-arrow-right"></i>
                    </button>
                </div>
            </div>

            <!-- 第三步：选择球台 -->
            <div class="form-section" id="section3" style="display: none;">
                <h5 class="mb-3">
                    <i class="bi bi-grid-3x3"></i> 选择球台
                </h5>
                <p class="text-muted mb-4">请选择可用的球台</p>

                <div id="tableList">
                    <div class="text-muted">请先完成时间选择</div>
                </div>

                <!-- 使用form字段而不是独立的hidden input -->
                {{ form.table_id }}

                <div class="text-end mt-3">
                    <button type="button" class="btn btn-outline-secondary me-2" onclick="prevStep(3)">
                        <i class="bi bi-arrow-left"></i> 上一步
                    </button>
                    <button type="button" class="btn btn-primary" onclick="nextStep(3)" disabled id="nextBtn3">
                        下一步 <i class="bi bi-arrow-right"></i>
                    </button>
                </div>
            </div>

            <!-- 第四步：确认预约 -->
            <div class="form-section" id="section4" style="display: none;">
                <h5 class="mb-3">
                    <i class="bi bi-check-circle"></i> 确认预约
                </h5>
                <p class="text-muted mb-4">请确认预约信息</p>

                <div id="reservationSummary">
                    <!-- 预约摘要将通过JavaScript填充 -->
                </div>

                <!-- 费用与余额信息 -->
                <div class="price-summary" id="priceSummary">
                    <h6 class="mb-3"><i class="bi bi-credit-card"></i> 费用信息</h6>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="d-flex justify-content-between mb-2">
                                <span>课程费用：</span>
                                <span id="courseFee">--</span>
                            </div>
                            <div class="d-flex justify-content-between mb-2">
                                <span>球台费用：</span>
                                <span id="tableFee">--</span>
                            </div>
                            <hr>
                            <div class="d-flex justify-content-between fw-bold">
                                <span>总计：</span>
                                <span id="totalFee" class="text-primary">--</span>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="d-flex justify-content-between mb-2">
                                <span>当前余额：</span>
                                <span id="currentBalance">--</span>
                            </div>
                            <div class="d-flex justify-content-between mb-2">
                                <span>扣费后余额：</span>
                                <span id="afterBalance">--</span>
                            </div>
                            <div id="balanceWarning" class="alert alert-warning mt-3" style="display: none;">
                                <i class="bi bi-exclamation-triangle"></i>
                                <span id="balanceWarningText"></span>
                            </div>
                            <div id="balanceError" class="alert alert-danger mt-3" style="display: none;">
                                <i class="bi bi-x-circle"></i>
                                余额不足，无法完成预约。请先充值。
                                <a href="{{ url_for('accounts.recharge') }}" class="alert-link">去充值</a>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 备注 -->
                <div class="mt-4">
                    <label class="form-label">备注信息</label>
                    {{ form.notes(class="form-control", placeholder="可填写特殊要求或说明...") }}
                    {% if form.notes.errors %}
                        <div class="text-danger small mt-1">
                            {% for error in form.notes.errors %}
                                {{ error }}
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>

                <div class="text-end mt-4">
                    <button type="button" class="btn btn-outline-secondary me-2" onclick="prevStep(4)">
                        <i class="bi bi-arrow-left"></i> 上一步
                    </button>
                    {{ form.submit(class="btn btn-success btn-lg", id="submitBtn") }}
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 加载遮罩 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="text-center">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <div class="mt-2">加载中...</div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentStep = 1;
let selectedCoach = null;
let selectedDate = null;
let selectedStartTime = null;
let selectedEndTime = null;
let selectedTable = null;
let currentBalance = 0;
let courseFee = 0;
let tableFee = 0;
let totalFee = 0;

// 选择教练
function selectCoach(coachId) {
    // 清除之前的选择
    document.querySelectorAll('.coach-card').forEach(card => {
        card.classList.remove('selected');
        card.querySelector('.bi-check-circle').style.display = 'none';
    });

    // 选择当前教练
    const selectedCard = document.querySelector(`[data-coach-id="${coachId}"]`);
    selectedCard.classList.add('selected');
    selectedCard.querySelector('.bi-check-circle').style.display = 'block';

    // 设置表单值
    document.querySelector('#coach_id').value = coachId;
    selectedCoach = coachId;

    // 启用下一步按钮
    document.getElementById('nextBtn1').disabled = false;
}

// 加载时间段
function loadTimeSlots() {
    const dateInput = document.querySelector('#reservation_date');
    const timeSlots = document.getElementById('timeSlots');

    if (!dateInput.value || !selectedCoach) {
        return;
    }

    selectedDate = dateInput.value;
    timeSlots.innerHTML = '<div class="text-muted">加载中...</div>';

    // 生成时间段（8:00-22:00，每30分钟一个）
    const slots = [];
    for (let hour = 8; hour < 22; hour++) {
        for (let minute = 0; minute < 60; minute += 30) {
            const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
            slots.push(timeStr);
        }
    }

    let slotsHtml = '';
    slots.forEach(time => {
        slotsHtml += `<div class="time-slot" data-time="${time}" onclick="selectTimeSlot('${time}')">${time}</div>`;
    });

    timeSlots.innerHTML = slotsHtml;
}

// 选择时间段
function selectTimeSlot(time) {
    // 清除之前的选择
    document.querySelectorAll('.time-slot').forEach(slot => {
        slot.classList.remove('selected');
    });

    // 选择当前时间段
    const selectedSlot = document.querySelector(`[data-time="${time}"]`);
    selectedSlot.classList.add('selected');

    selectedStartTime = time;
    document.querySelector('#start_time').value = time;

    // 更新结束时间
    updateEndTime();
}

// 更新结束时间
function updateEndTime() {
    if (!selectedStartTime) return;

    const duration = parseInt(document.getElementById('durationSelect').value);
    const [hours, minutes] = selectedStartTime.split(':').map(Number);
    const startDate = new Date();
    startDate.setHours(hours, minutes, 0);

    const endDate = new Date(startDate.getTime() + duration * 60000);
    const endTimeStr = `${endDate.getHours().toString().padStart(2, '0')}:${endDate.getMinutes().toString().padStart(2, '0')}`;

    selectedEndTime = endTimeStr;
    document.querySelector('#end_time').value = endTimeStr;

    // 启用下一步按钮
    document.getElementById('nextBtn2').disabled = false;

    // 加载可用球台
    loadAvailableTables();
}

// 加载可用球台
function loadAvailableTables() {
    if (!selectedDate || !selectedStartTime || !selectedEndTime) {
        return;
    }

    const tableList = document.getElementById('tableList');
    tableList.innerHTML = '<div class="text-muted">加载可用球台...</div>';

    fetch(`/student-reservations/api/available-tables?date=${selectedDate}&start_time=${selectedStartTime}&end_time=${selectedEndTime}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const tables = data.data.tables;
                if (tables.length === 0) {
                    tableList.innerHTML = '<div class="alert alert-warning">该时间段暂无可用球台</div>';
                } else {
                    let tablesHtml = '';
                    tables.forEach(table => {
                        tablesHtml += `
                            <div class="table-card" data-table-id="${table.id}" onclick="selectTable(${table.id})">
                                <div class="row align-items-center">
                                    <div class="col">
                                        <h6 class="mb-1">${table.name}</h6>
                                        <small class="text-muted">${table.status_display || '可用'}</small>
                                    </div>
                                    <div class="col-auto">
                                        <i class="bi bi-check-circle text-success" style="display: none;"></i>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    tableList.innerHTML = tablesHtml;
                }
            } else {
                tableList.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            tableList.innerHTML = '<div class="alert alert-danger">加载球台失败</div>';
        });
}

// 选择球台
function selectTable(tableId) {
    // 清除之前的选择
    document.querySelectorAll('.table-card').forEach(card => {
        card.classList.remove('selected');
        card.querySelector('.bi-check-circle').style.display = 'none';
    });

    // 选择当前球台
    const selectedCard = document.querySelector(`[data-table-id="${tableId}"]`);
    selectedCard.classList.add('selected');
    selectedCard.querySelector('.bi-check-circle').style.display = 'block';

    // 设置表单值
    document.querySelector('#table_id').value = tableId;
    selectedTable = tableId;

    // 启用下一步按钮
    document.getElementById('nextBtn3').disabled = false;
}

// 下一步
function nextStep(step) {
    if (step === 3) {
        // 生成预约摘要
        generateReservationSummary();
    }

    // 隐藏当前步骤
    document.getElementById(`section${step}`).style.display = 'none';

    // 显示下一步骤
    document.getElementById(`section${step + 1}`).style.display = 'block';

    // 更新步骤指示器
    updateStepIndicator(step + 1);

    currentStep = step + 1;
}

// 上一步
function prevStep(step) {
    // 隐藏当前步骤
    document.getElementById(`section${step}`).style.display = 'none';

    // 显示上一步骤
    document.getElementById(`section${step - 1}`).style.display = 'block';

    // 更新步骤指示器
    updateStepIndicator(step - 1);

    currentStep = step - 1;
}

// 更新步骤指示器
function updateStepIndicator(activeStep) {
    for (let i = 1; i <= 4; i++) {
        const stepElement = document.getElementById(`step${i}`);
        stepElement.classList.remove('active', 'completed');

        if (i < activeStep) {
            stepElement.classList.add('completed');
        } else if (i === activeStep) {
            stepElement.classList.add('active');
        }
    }
}

// 生成预约摘要
function generateReservationSummary() {
    // 确保form字段有正确的值
    if (selectedCoach) {
        document.getElementById('coach_id').value = selectedCoach;
    }
    if (selectedTable) {
        document.getElementById('table_id').value = selectedTable;
    }

    console.log('生成摘要 - selectedCoach:', selectedCoach, 'selectedTable:', selectedTable);
    console.log('生成摘要 - coach_id value:', document.getElementById('coach_id').value);
    console.log('生成摘要 - table_id value:', document.getElementById('table_id').value);

    // 验证必要字段
    if (!selectedCoach || !selectedTable) {
        console.error('缺少必要字段 - coach:', selectedCoach, 'table:', selectedTable);
        return;
    }

    const coachName = document.querySelector(`[data-coach-id="${selectedCoach}"]`).querySelector('h6').textContent;
    const tableName = document.querySelector(`[data-table-id="${selectedTable}"]`).querySelector('h6').textContent;

    const summaryHtml = `
        <div class="row">
            <div class="col-md-6">
                <div class="card h-100">
                    <div class="card-body">
                        <h6 class="card-title"><i class="bi bi-person-check"></i> 教练信息</h6>
                        <p class="card-text">${coachName}</p>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card h-100">
                    <div class="card-body">
                        <h6 class="card-title"><i class="bi bi-grid-3x3"></i> 球台信息</h6>
                        <p class="card-text">${tableName}</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-md-4">
                <div class="card h-100">
                    <div class="card-body text-center">
                        <h6 class="card-title"><i class="bi bi-calendar3"></i> 预约日期</h6>
                        <p class="card-text">${selectedDate}</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card h-100">
                    <div class="card-body text-center">
                        <h6 class="card-title"><i class="bi bi-clock"></i> 上课时间</h6>
                        <p class="card-text">${selectedStartTime} - ${selectedEndTime}</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card h-100">
                    <div class="card-body text-center">
                        <h6 class="card-title"><i class="bi bi-hourglass-split"></i> 课程时长</h6>
                        <p class="card-text">${document.getElementById('durationSelect').selectedOptions[0].text}</p>
                    </div>
                </div>
            </div>
        </div>
    `;

    document.getElementById('reservationSummary').innerHTML = summaryHtml;

    // 加载费用信息和余额验证
    loadPriceAndBalance();
}

// 加载费用信息和余额验证
function loadPriceAndBalance() {
    const duration = parseInt(document.getElementById('durationSelect').value);

    // 显示加载状态
    document.getElementById('courseFee').textContent = '计算中...';
    document.getElementById('tableFee').textContent = '计算中...';
    document.getElementById('totalFee').textContent = '计算中...';
    document.getElementById('currentBalance').textContent = '加载中...';

    // 构造请求参数
    const params = new URLSearchParams({
        coach_id: selectedCoach,
        table_id: selectedTable,
        date: selectedDate,
        start_time: selectedStartTime,
        end_time: selectedEndTime,
        duration: duration
    });

    fetch(`/student-reservations/api/calculate-fee?${params}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const feeData = data.data;
                courseFee = feeData.course_fee;
                tableFee = feeData.table_fee;
                totalFee = feeData.total_fee;
                currentBalance = feeData.current_balance;

                // 更新费用显示
                document.getElementById('courseFee').textContent = `¥${courseFee.toFixed(2)}`;
                document.getElementById('tableFee').textContent = `¥${tableFee.toFixed(2)}`;
                document.getElementById('totalFee').textContent = `¥${totalFee.toFixed(2)}`;
                document.getElementById('currentBalance').textContent = `¥${currentBalance.toFixed(2)}`;

                const afterBalance = currentBalance - totalFee;
                document.getElementById('afterBalance').textContent = `¥${afterBalance.toFixed(2)}`;

                // 余额验证
                validateBalance(afterBalance);

            } else {
                showError(data.message || '费用计算失败');
                // 设置默认值
                courseFee = 0;
                tableFee = 0;
                totalFee = 0;
                updateFeeDisplay();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('费用计算失败，请重试');
            // 设置默认值
            courseFee = 0;
            tableFee = 0;
            totalFee = 0;
            updateFeeDisplay();
        });
}

// 更新费用显示（默认值）
function updateFeeDisplay() {
    document.getElementById('courseFee').textContent = `¥${courseFee.toFixed(2)}`;
    document.getElementById('tableFee').textContent = `¥${tableFee.toFixed(2)}`;
    document.getElementById('totalFee').textContent = `¥${totalFee.toFixed(2)}`;
    document.getElementById('currentBalance').textContent = `¥${currentBalance.toFixed(2)}`;
    document.getElementById('afterBalance').textContent = `¥${(currentBalance - totalFee).toFixed(2)}`;
}

// 余额验证
function validateBalance(afterBalance) {
    const balanceWarning = document.getElementById('balanceWarning');
    const balanceError = document.getElementById('balanceError');
    const submitBtn = document.getElementById('submitBtn');

    // 隐藏所有提示
    balanceWarning.style.display = 'none';
    balanceError.style.display = 'none';

    if (afterBalance < 0) {
        // 余额不足，无法预约
        balanceError.style.display = 'block';
        submitBtn.disabled = true;
        submitBtn.textContent = '余额不足';
    } else if (afterBalance < 50) {
        // 余额较低，给予警告
        balanceWarning.style.display = 'block';
        document.getElementById('balanceWarningText').textContent =
            `预约后余额将低于50元，建议及时充值以避免影响后续预约。`;
        submitBtn.disabled = false;
        submitBtn.textContent = '确认预约';
    } else {
        // 余额充足
        submitBtn.disabled = false;
        submitBtn.textContent = '确认预约';
    }
}

// 显示错误消息
function showError(message) {
    const errorDiv = document.getElementById('errorMessage');
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
    setTimeout(() => {
        errorDiv.style.display = 'none';
    }, 5000);
}

// 显示成功消息
function showSuccess(message) {
    const successDiv = document.getElementById('successMessage');
    successDiv.textContent = message;
    successDiv.style.display = 'block';
    setTimeout(() => {
        successDiv.style.display = 'none';
    }, 5000);
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 设置最小日期为今天
    const today = new Date();
    const minDate = today.toISOString().split('T')[0];
    document.querySelector('#reservation_date').setAttribute('min', minDate);

    // 设置最大日期为30天后
    const maxDate = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000);
    document.querySelector('#reservation_date').setAttribute('max', maxDate.toISOString().split('T')[0]);

    // 添加表单提交验证
    const form = document.getElementById('reservationForm');
    form.addEventListener('submit', function(e) {
        // 再次确保字段值正确设置
        if (selectedCoach) {
            document.getElementById('coach_id').value = selectedCoach;
        }
        if (selectedTable) {
            document.getElementById('table_id').value = selectedTable;
        }

        const coachId = document.getElementById('coach_id').value;
        const tableId = document.getElementById('table_id').value;

        console.log('提交验证 - coach_id:', coachId, 'table_id:', tableId);
        console.log('提交验证 - selectedCoach:', selectedCoach, 'selectedTable:', selectedTable);

        if (!coachId || coachId === '') {
            e.preventDefault();
            showError('请选择教练');
            // 跳转到第1步让用户选择教练
            document.getElementById('section4').style.display = 'none';
            document.getElementById('section1').style.display = 'block';
            updateStepIndicator(1);
            currentStep = 1;
            return false;
        }

        if (!tableId || tableId === '') {
            e.preventDefault();
            showError('请选择球台');
            // 跳转到第3步让用户选择球台
            document.getElementById('section4').style.display = 'none';
            document.getElementById('section3').style.display = 'block';
            updateStepIndicator(3);
            currentStep = 3;
            return false;
        }

        // 验证通过，允许提交
        console.log('验证通过，提交表单');
        return true;
    });
});
</script>
{% endblock %}